<?php
// 欠款系统
!defined('IN_SYSTEM') && exit('Access denied');

class loanControlPage extends commonControlPage 
{
	//欠款申请提交
    public function postModule() 
	{
		if (POST && AJAX) {
			$price = $_POST['price'];
			$mark = htmlspecialchars($_POST['mark']);
			
			if (!preg_match('/^(\d|[1-9]\d{0,9})(\.\d{1,2})?$/',$price)) {
				$this->outputJson(0,'金额格式不正确');
			}

            $next_uid = $_POST['next_uid'];
            if (!$_ENV['db']->fetchCol("SELECT node_id FROM admincp_member_perm WHERE node_id = '{$_ENV['config']['loan_post_node']}' AND uid = '{$next_uid}'")) {
                $this->outputJson(0,'制定的操作员无权限');
            }
			$param = array();
			$param['price'] = $price;
			$param['mark'] = $mark;
			$param['uid'] = $this->user['uid'];
			$param['username'] = $this->user['username'];
			$param['nickname'] = $this->user['nickname'];
			$param['created_time'] = $_ENV['time'];
            $param['co_member_id'] = $next_uid;
			$param['audit_state'] ='0';   //欠款申请单据状态 未审核
			$_ENV['db']->runSql("INSERT INTO `loan` ".$this->buildSql($param));
			$this->outputJson(1,'已提交审核，请耐心等待');
		}
        $user_list = $_ENV['db']->fetchAll("SELECT m.username,m.nickname,m.uid FROM `admincp_member` as m LEFT JOIN admincp_member_perm as p ON m.uid=p.uid WHERE p.node_id = '{$_ENV['config']['loan_post_audit_node']}'");
		
		$this->view->total_loal  = $_ENV['db']->fetchCol("SELECT total_loal FROM admincp_member_detail WHERE uid = {$this->user['uid']} ");
		
        $this->view->users = $user_list;
        $this->showMainPage('admincp/loan_post');
    }

	//欠款列表
	public function listModule() 
	{
		if (preg_match('/[0-9]+/',$_GET['loan_id'])) {
			$loan = $_ENV['db']->fetch("SELECT * FROM `loan` WHERE `loan_id` = '{$_GET['loan_id']}'");
			$this->view->audit_state = $this->GetOrderStatus($loan['audit_state']);
			$this->view->loan = $loan;
			$this->showMainPage('admincp/loan_desc');
		} else {
			$this->call('doLoanList');
			$this->showMainPage('admincp/loan_list');
		}
	}

	//我的欠款单
    public function myModule() 
	{
        if (!empty($_GET['loan_id'])) 
		{
			$total = $_ENV['db']->fetchCol("SELECT count(*) FROM repayment where loan_id = '{$_GET['loan_id']}' ");
			$pager = new class_pager();
			$pager->setConfig((int)$_GET['page_no'],$total);
			$pager->setUrl("?app=loan&mod=my&page_no=tpt","tpt");
			$lists = $_ENV['db']->fetchAll("SELECT * FROM repayment where loan_id = '{$_GET['loan_id']}'  order by rid desc limit ".$pager->getLimit()." offset ".$pager->getOffset());
			$this->view->pager = $pager->output();
			$this->view->lists = $lists;
            $loan = $_ENV['db']->fetch("SELECT * FROM loan WHERE loan_id = '".$_GET['loan_id']."'");
			$this->view->audit_state = $this->GetOrderStatus($loan['audit_state']);
		    $this->view->loan = $loan;
            $this->showMainPage('admincp/loan_mydesc');
        } 
		else 
		{
			$this->view->addScript('rili');
			$page = (int)$_GET['page_no'];
			$_GET['page_no'] = 'TPT';
				
			$type = $_GET['type']? $_GET['type']:'m';
			
			if($type=='m')
			{  //我的欠款记录
				$where = ' 1 and uid="'.$this->user['uid'].'" ';
				if($_GET['start_date'] && $_GET['end_date'])
				{
					$date = $this->checkDateFormat();
					$start_date = $date['s'];
					$end_date   = $date['e'];
					$where .= ' and created_time between '.$start_date.' and '.$end_date;
				}
				$this->view->maction = ' class="active" ';
			}
			else if($type=='s')
			{
				$where = '1 and audit1_uid="'.$this->user['uid'].'" ';
				if($_GET['start_date'] && $_GET['end_date'])
				{
					$date = $this->checkDateFormat();
					$start_date = $date['s'];
					$end_date   = $date['e'];
					$where .= ' and created_time between '.$start_date.' and '.$end_date;
				}
				$this->view->saction = ' class="active" ';
			}
			else if($type=='f')
			{
				$where = '1 and audit2_uid="'.$this->user['uid'].'" ';
				if($_GET['start_date'] && $_GET['end_date'])
				{
					$date = $this->checkDateFormat();
					$start_date = $date['s'];
					$end_date   = $date['e'];
					$where .= ' and created_time between '.$start_date.' and '.$end_date;
				}
				$this->view->faction = ' class="active" ';
			}
			
		
			$list =  $this->PrePage('loan','loan_id',$where,$page,'loan_id desc');
			foreach((array)$list as $key=>$value)
			{
				$list[$key]['audit_state'] = $this->GetOrderStatus($value['audit_state']);
			}
			$this->view->loan_list = $list;
			$this->view->type = $type;
			
			/*[当前借款总数]*/
			$this->view->total_loal  = $_ENV['db']->fetchCol("SELECT total_loal FROM admincp_member_detail WHERE uid = {$this->user['uid']} ");
		
        	$this->showMainPage('admincp/loan_mylist');
		}
    }

	//不批准欠款申请
	public function notallowModule()
	{
		if (AJAX) 
		{
			$vid = $_GET['vid'];
			$step = $_GET['step'];
			switch($step) 
			{
				case '1':
					$param['audit1_uid'] = $this->user['uid'];
					$param['audit1_username'] = $this->user['username'];
					$param['audit1_dateline'] = $_ENV['time'];
					break;
				case '2':
					$param['audit2_uid'] = $this->user['uid'];
					$param['audit2_username'] = $this->user['username'];
					$param['audit2_dateline'] = $_ENV['time'];
					break;
			}
			$param['audit_state'] = '3';   //状态是不批准
			$_ENV['db']->runSql("UPDATE `loan` ".$this->buildSql($param)." WHERE `loan_id` = '{$vid}'");
			$this->outputJson(1,'操作成功');
		}
	}
	/*[魔术方法实现审核流程]*/
    public function __call($func,$args) 
	{
        if (substr($func,0,5) == 'audit' && substr($func,5,1) > 0 && substr($func,5,1) < 3) 
		{
            $step = substr($func,5,1);
			if (preg_match('/[0-9]+/',$_GET['loan_id'])) 
			{
				$loan = $_ENV['db']->fetch("SELECT * FROM `loan` WHERE `loan_id` = '{$_GET['loan_id']}'");
				if (!$loan) $this->showMessage('指定的对象不存在',AJAX?0:'back');
				$node_id = $_ENV['config']['loan_audit_nodes'][$step];
				if (POST && AJAX) 
				{
					$param = array();
					$param['audit_state'] = $step;
					$next_uid = (int)$_POST['next_uid'];
					$param['co_member_id'] = $next_uid;
					switch($step) {
						case '1':
							$param['audit1_uid'] = $this->user['uid'];
							$param['audit1_username'] = $this->user['username'];
							$param['audit1_dateline'] = $_ENV['time'];
						break;

						case '2':
							$param['audit2_uid'] = $this->user['uid'];
							$param['audit2_username'] = $this->user['username'];
							$param['audit2_dateline'] = $_ENV['time'];
						break;
					}
					# 检测指定的下级用户是否有权限
					if ($step!=2) 
					{
						$cr = $_ENV['db']->fetchCol("SELECT node_id FROM admincp_member_perm WHERE node_id = '{$node_id}' AND uid = '{$next_uid}'");
						if (!$cr) $this->outputJson(0,'指定的下级操作员没有足够的权限');
					}
					else
					{//等于2,通过复审，统计借款总额
						# 更新目标用户的总欠款金额 和 借款总额
                    	$_ENV['db']->runSql("update admincp_member_detail set loan_price=loan_price+{$loan['price']} ,total_loal=total_loal+{$loan['price']} where uid = '{$loan['uid']}'");
					}
					$_ENV['db']->runSql("UPDATE `loan` ".$this->buildSql($param)." WHERE `loan_id` = '{$_GET['loan_id']}'");
					$this->outputJson(1,'操作成功');
				}

				// 获取下级操作员列表
				$next_user_list = $_ENV['db']->fetchAll("SELECT m.username,m.nickname,m.uid FROM `admincp_member` as m LEFT JOIN admincp_member_perm as p ON m.uid=p.uid WHERE p.node_id = '{$node_id}'");
				switch ($step) {
					case '1':
						$operation = '<input type="submit" value="审核通过，转二级审核"/>';
					break;
					case '2':
						$operation = '<input type="submit" value="审核通过"/>';
					break;
				}
				
				/*[当前借款总数]*/
				$this->view->total_loal  = $_ENV['db']->fetchCol("SELECT total_loal FROM admincp_member_detail WHERE uid = {$this->user['uid']} ");
		
		
				$this->view->audit_state = $this->GetOrderStatus($loan['audit_state']);
				$this->view->operation = $operation;
				$this->view->next_user_list = $next_user_list;
				$this->view->step = $step-1;
				$this->view->loan = $loan;
				$this->showMainPage('admincp/loan_desc');
			} 
			else 
			{
				$this->doLoanList($step-1,$this->user['uid']);
			    $this->showMainPage('admincp/loan_list');
			}
        } 
		else 
		{
            parent::__call($func,$args);
        }
    }

	public function call($method) {
		$allowed = array(
				'doLoanList'
			);
		if (in_array($method,$allowed)) {
			call_user_func(array($this,$method));
		}
	}

	//获得欠款单状态
	private function GetOrderStatus($code)
	{
		switch($code)
		{
			case '0':  return '<span style="color:red; font-size:14px;">未审批</span>';  break;
			case '1':  return '<span style="color:blue; font-size:14px;">未复审</span>';  break;
			case '2':  return '<span style="color:blue; font-size:14px;">未还清</span>';  break;
			case '3':  return '<span style="color:red; font-size:14px;">不批准</span>';  break;
			case '4':  return '<span style="color:green; font-size:14px;">已还清</span>';  break;
		}
		return '未审批';
	}

	private function doLoanList($audit_state='',$uid='') 
	{
		$where = '1';
		$page = (int)$_GET['page_no'];
		$_GET['page_no'] = 'TPT';
		if ($audit_state || $audit_state=='0') {
			$where .= ' and `audit_state` = '.$audit_state;
		}
        if ($uid && !in_array($this->user['uid'],$_ENV['config']['superadmin'])) {
            $where .= ' and `co_member_id` = '.$uid;
        }
		$this->view->loan_list = $this->PrePage('loan','loan_id',$where,$page,'loan_id desc');
	}
	
	//验证时间格式
	/* 用于查询的时间验证
	 * (1) 结束时间必须小于开始时间
	 * (2) 所选日期时间段不能超过1年
	*/
	private function checkDateFormat() 
	{
        $start_date = $_GET['start_date'];
        $end_date = $_GET['end_date'];
		$this->view->start_date = $start_date;   //开始时间
		$this->view->end_date = $end_date;       //结束时间
        if (!ValidateDate($start_date) || !ValidateDate($end_date)) {
            $this->showMessage('日期格式错误','back');
        }
        $start_date = strtotime($start_date);
        $end_date = strtotime($end_date." 23:59:59");
        if ($start_date > $end_date) {
            $this->showMessage('结束时间必须小于开始时间','back');
        }
        if (($end_date-$start_date) > 31536000) {
            $this->showMessage('所选日期时间段超过了1年','back');
        }
        return array('s'=>$start_date,'e'=>$end_date);
    }
	
	// 借款统计报表
	public function reportModule()
	{
		//日期选择控件JS
		$this->view->addScript('rili');
        $this->view->addScript('autocomplete');
		
		$where = " 1 ";
		 $sel_UName = $_GET['searchUser'];      //查询人名称	
		//$sel_phase = $_GET['searchPhase'];    //项目阶段
		//$sel_Item = $_GET['searchItem'];      //选择项目
		if ($sel_UName ) 
		{   //通过用户名获得用户ID （UID）
			$sel_UID = $_ENV['db']->fetchCol("SELECT m.uid FROM `admincp_member` as m where username='". $sel_UName ."'");
        	$where .= ' and `uid` = '.$sel_UID;
       	}
		if($_GET['start_date'] && $_GET['end_date'])
		{
			$date = $this->checkDateFormat();
			$start_date = $date['s'];
			$end_date = $date['e'];
			$where .= ' and created_time between '.$start_date.' and '.$end_date;
		}
		$loan = $_ENV['db']->fetchAll("SELECT * FROM `loan` WHERE {$where} order by created_time asc,loan_id desc");
		$result = array();
		foreach ((array)$loan as $key=>$val) 
		{
			$result[$val['uid']]['items'][] = $val;
			$result[$val['uid']]['total_price']     += $val['price'];
			$result[$val['uid']]['total_arr_price'] += $val['arr_price'];
			$result[$val['uid']]['nickname'] = $val['nickname'];
		}
		$this->view->result = $result;
		$this->view->sel_UName = $sel_UName;
		$this->showMainPage('admincp/loan_report');
	}
	
	// 借款汇总报表
	public function report2Module()
	{
        $this->view->addScript('autocomplete');
		$where = " 1 ";
		 $sel_UName = $_GET['searchUser'];      //查询人名称	
		//$sel_phase = $_GET['searchPhase'];    //项目阶段
		//$sel_Item = $_GET['searchItem'];      //选择项目
		if ($sel_UName ) 
		{   //通过用户名获得用户ID （UID）
			$sel_UID = $_ENV['db']->fetchCol("SELECT m.uid FROM `admincp_member` as m where username='". $sel_UName ."'");
        	$where .= ' and `uid` = '.$sel_UID;
       	}
		$loan = $_ENV['db']->fetchAll("SELECT * FROM `loan` WHERE {$where} order by created_time asc,loan_id desc");
		$result = array();
		foreach ((array)$loan as $key=>$val) 
		{
			$result[$val['uid']]['items'][] = $val;
			$result[$val['uid']]['total_price']     += $val['price'];
			$result[$val['uid']]['total_arr_price'] += $val['arr_price'];
			$result[$val['uid']]['total_count'] = count($loan);
			$result[$val['uid']]['nickname'] = $val['nickname'];
		}
		$this->view->result = $result;
		$this->view->sel_UName = $sel_UName;
		$this->showMainPage('admincp/loan_report2');
	}
	
}